﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using MimiDouban.Abstract;
using System.Threading;
using System.Windows.Threading;
using System.IO;
using System.Windows;

namespace MimiDouban.UI.HttpInputUI
{
    /// <summary>
    /// 用与处理手机遥控的类
    /// </summary>
    public class HttpInputUI : DispatcherObject, IInputUI
    {
        /// <summary>
        /// 端口号
        /// </summary>
        private const int port = 8099;

        /// <summary>
        /// URL路径
        /// </summary>
        private const string path = "mimi/";

        /// <summary>
        /// HTTP监听器
        /// </summary>
        private HttpListener listener = null;

        /// <summary>
        /// 工作线程
        /// </summary>
        private Thread workThread;

        public HttpInputUI()
        {
            workThread = new Thread(new ThreadStart(service));//新建线程
            workThread.IsBackground = true;//设置为后台线程
            workThread.Start();//开始线程
        }

        private void service()
        {
            try
            {
                if (!HttpListener.IsSupported)//如果不支持，则返回
                {
                    return;
                }

                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress[] myips = IpEntry.AddressList;//获取所有的IP地址

                List<string> prefixes = new List<string>();
                prefixes.Add("http://localhost:" + port + "/" + path);
                prefixes.Add("http://127.0.0.1:" + port + "/" + path);
                for (int i = 0; i < myips.Length; i++)
                {
                    if (myips[i].GetAddressBytes().Length > 4)//目前不支持Ipv6的地址
                    {
                        continue;
                    }
                    prefixes.Add("http://" + myips[i].ToString() + ":" + port + "/" + path);
                }
                if (prefixes == null || prefixes.Count == 0)
                    throw new ArgumentException("prefixes");
                listener = new HttpListener();
                foreach (string s in prefixes)
                {
                    try
                    {
                        listener.Prefixes.Add(s);
                    }
                    catch
                    {
                    }
                }
                listener.Start();

            }
            catch
            {
                return;
            }

            while (true)//采用单线程轮流服务，不支持多线程同时操作
            {
                try
                {
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;
                    HttpListenerResponse response = context.Response;

                    string message = request.QueryString["msg"];//获取message参数，执行相应的操作
                    if (!String.IsNullOrEmpty(message))
                    {
                        if (message == "like")
                        {
                            this.Dispatcher.Invoke(LikeClicked, new object[] { });
                        }
                        else if (message == "dislike")
                        {
                            this.Dispatcher.Invoke(DisikeClicked, new object[] { });
                        }
                        else if (message == "next")
                        {
                            this.Dispatcher.Invoke(NextClicked, new object[] { });
                        }
                        else if (message == "pause")
                        {
                            this.Dispatcher.Invoke(PauseClicked, new object[] { });
                        }
                    }

                    string reqPath = request.RawUrl.ToString();//处理静态文件获取的工作
                    string filename;
                    if (reqPath.IndexOf("?") >= 0)
                    {
                        filename = reqPath.Substring(0, reqPath.IndexOf("?"));
                    }
                    else
                    {
                        filename = reqPath;
                    }
                    filename = filename.Substring(path.Length + 1);//得到文件名

                    byte[] buffer = new byte[] { };//默认是404，即文件未找到
                    string temp = "<html><body><h1>File Not Found</h1></body></html>";
                    buffer = System.Text.Encoding.UTF8.GetBytes(temp);
                    response.ContentType = "text/html";
                    response.StatusCode = 404;

                    if (filename.EndsWith("html"))//读取html文件
                    {
                        try
                        {
                            FileStream file = File.Open("Resources\\html\\" + filename, FileMode.Open);

                            buffer = new byte[file.Length];
                            file.Read(buffer, 0, (int)file.Length);
                            file.Close();
                            response.ContentType = "text/html";
                            response.StatusCode = 200;
                        }
                        catch
                        {

                        }
                    }else if(filename.EndsWith("png"))//读取图片文件
                    {
                        try
                        {
                            FileStream file = File.Open("Resources\\images\\" + filename, FileMode.Open);
                            buffer = new byte[file.Length];
                            file.Read(buffer, 0, (int)file.Length);
                            file.Close();
                            response.ContentType = "image/png";
                            response.StatusCode = 200;
                        }
                        catch
                        {

                        }
                    }


                    response.ContentLength64 = buffer.Length;//发送响应
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                }
                catch
                {
                    listener.Stop();
                    break;
                }
            }
        }

        #region IInputUI Members

        public event ButtonClickHandler LikeClicked;

        public event ButtonClickHandler DisikeClicked;

        public event ButtonClickHandler NextClicked;

        public event ButtonClickHandler PauseClicked;

        public event ButtonClickHandler CloseClicked;

        public event ChannelChooseHandler ChannelChoosen;

        public event VolumeChangedHandler VolumeChanged;

        public event UserLoginHandler UserLogin;

        public void end()
        {
            this.workThread.Abort();//结束时接收线程
        }

        #endregion
    }
}
